package tws

import (
	"log"
	"strings"

	"github.com/gin-gonic/gin"
)

type RouterItem struct {
	Path   string
	Method string
	Handle func(ctx *Context)
}
type RouterManager struct {
	engine  *gin.Engine
	routers map[string]*RouterItem
}

func NewRouterManager(engine *gin.Engine) *RouterManager {
	return &RouterManager{
		engine:  engine,
		routers: map[string]*RouterItem{},
	}
}

func (_this *RouterManager) Register(id string, handle func(ctx *Context)) {
	if id == "" {
		log.Fatal("id is invalid")
		return
	}
	if handle == nil {
		log.Fatal("handle is nil")
		return
	}
	routerID := _getRouterValueByIndex(0, id)
	routerItem := &RouterItem{
		Path:   _getRouterValueByIndex(1, id),
		Method: _getRouterValueByIndex(2, id),
		Handle: handle,
	}
	_this.routers[routerID] = routerItem
}

func _getRouterValueByIndex(index int, path string) string {
	return strings.Split(path, ":")[index]
}

func (_this *RouterManager) BindRouters() {
	routers := _this.routers
	for id, r := range routers {
		url := "/" + id + "/" + r.Path
		if r.Method == "get" {
			_this.engine.GET(url, func(ctx *gin.Context) {
				Handle(r.Handle)
			})
		} else if r.Method == "post" {
			_this.engine.POST(url, func(ctx *gin.Context) {
				Handle(r.Handle)
			})
		} else {
			return
		}
	}
}
